package com.vnp.cooking;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.utils.KeyboardHelper;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

public class TaoMonAnChupAnhActivity extends SherlockFragmentActivity implements OnClickListener, OnEditorActionListener{
	
	// duong dan cua anh
	Uri fileUri;
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
    ImageView imgPreview;
    // Khai bao nut back vao next
    ImageButton btnBack, btnNextStep;
    // nhap ten mon an
    EditText edtTenMonAn;
    // Object mon an
    ObjCookpad objCookpad = new ObjCookpad();
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.activity_tao_mon_an_chup_anh);
//		imgPreview = (ImageView) findViewById(R.id.img_anh_chup_mon_an);
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnNextStep = (ImageButton) findViewById(R.id.btn_next_step);
		edtTenMonAn = (EditText) findViewById(R.id.edt_ten_mon);
		
		// set su kien click cho cac nut
		btnBack.setOnClickListener(this);
		btnNextStep.setOnClickListener(this);
		edtTenMonAn.setOnEditorActionListener(this);
		
		// xu li khi nhap ten mon an
		edtTenMonAn.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_WORDS);
		edtTenMonAn.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		
	}

	// check camera
	public boolean isDeviceSupport() {
		if (getApplicationContext().getPackageManager()
				.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			// this device has camera
			captureImage();
			return true;
		} else {
			// no camera on device
			return false;
		}
	}
	
	// ham chup anh
	public void captureImage() {
		Intent t = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
		 
	    t.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
	 
	    // start the image capture Intent
	    startActivityForResult(t, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
	}
	
	/**
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
	    return Uri.fromFile(getOutputMediaFile(type));
	}
	 
	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {
	 
	    // External sdcard location
	    File mediaStorageDir = new File(
	            Environment
	                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
	            IMAGE_DIRECTORY_NAME);
	 
	    // Create the storage directory if it does not exist
	    if (!mediaStorageDir.exists()) {
	        if (!mediaStorageDir.mkdirs()) {
	            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
	                    + IMAGE_DIRECTORY_NAME + " directory");
	            return null;
	        }
	    }
	 
	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
	            Locale.getDefault()).format(new Date());
	    File mediaFile;
	    if (type == MEDIA_TYPE_IMAGE) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator
	                + "IMG_" + timeStamp + ".jpg");
	    } else if (type == MEDIA_TYPE_VIDEO) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator
	                + "VID_" + timeStamp + ".mp4");
	    } else {
	        return null;
	    }
	 
	    return mediaFile;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				finish();
	           Toast.makeText(getApplicationContext(),"User cancelled image capture", Toast.LENGTH_SHORT)
	                    .show();
			} else {
				// failed to capture image
	           Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
	                    .show();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/*
     * Display image from a path to ImageView
     */
    private void previewCapturedImage() {
        try {
            // hide video preview
 
            imgPreview.setVisibility(View.VISIBLE);
 
            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();
 
            // downsizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 8;
 
            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                    options);
			objCookpad.setUrlImageCookpad(fileUri.toString());

 
            imgPreview.setImageBitmap(bitmap);
            KeyboardHelper.displaySoftKeyboard(getApplicationContext(), edtTenMonAn);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_next_step :
			checkNextStep();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		checkNextStep();
		return true;
	}
	
	// check buoc di buoc tiep theo
	public void checkNextStep() {
		if (TextUtils.isEmpty(edtTenMonAn.getText().toString())) {
			Toast.makeText(TaoMonAnChupAnhActivity.this, "Bạn chưa nhập tên món ăn", Toast.LENGTH_SHORT).show();
		} else {
			objCookpad.setNameCookpad(edtTenMonAn.getText().toString());
			// truyen du lieu tu ben chup anh sang
			Intent t = new Intent(TaoMonAnChupAnhActivity.this, TaoMonAnChonLoaiMonActivity.class);
			t.putExtra("objCookpad", objCookpad);
			startActivity(t);
		}
	}
}
